package com.sk.sourcecircle.activity.home.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dyhdyh.widget.loading.dialog.LoadingDialog;
import com.sk.sourcecircle.R;
import com.sk.sourcecircle.activity.login.LoginActivity;
import com.sk.sourcecircle.adapter.GroupListAdapter;
import com.sk.sourcecircle.adapter.PepAdapter;
import com.sk.sourcecircle.base.BaseActivity;
import com.sk.sourcecircle.callback.HandleDataCallBack;
import com.sk.sourcecircle.dialog.TipDialogFragment;
import com.sk.sourcecircle.entity.GroupListBean;
import com.sk.sourcecircle.entity.PepListBean;
import com.sk.sourcecircle.utils.AppApi;
import com.sk.sourcecircle.utils.MyUtils;
import com.sk.sourcecircle.utils.SnackUtils;
import com.sk.sourcecircle.view.EasyLoadingMoreView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by sk on 2017/12/26.
 */

public class SearchToAddActivity extends BaseActivity implements BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.RequestLoadMoreListener, HandleDataCallBack, BaseQuickAdapter.OnItemChildClickListener {
    @BindView(R.id.ed_search)
    EditText edSearch;
    @BindView(R.id.cancel)
    TextView cancel;
    @BindView(R.id.friend)
    TextView friend;
    @BindView(R.id.circle_ll)
    TextView circleLl;
    @BindView(R.id.tip_ll)
    LinearLayout tipLl;
    @BindView(R.id.pep_ryc)
    RecyclerView pepRyc;
    @BindView(R.id.group_ryc)
    RecyclerView groupRyc;
    private PepAdapter adapter;
    private GroupListAdapter groupListAdapter;
    private List<PepListBean.DataBeanX.DataBean> pepDataList = new ArrayList<>();
    private List<GroupListBean.DataBean> groupDataList = new ArrayList<>();
    private int what;
    private int page = 1;
    private String searchString = "";
    private boolean isLoadMore = false;
    private LoadingDialog loadingDialog;
    private int postion;

    @Override
    protected int getContentView() {
        return R.layout.activity_search_to_add;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        loadingDialog = MyUtils.getLoadingDialog(mContext, false);

        edSearch.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    // 先隐藏键盘
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(getCurrentFocus()
                                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    //进行搜索操作的方法，在该方法中可以加入mEditSearchUser的非空判断
                    if (edSearch.getText().toString().length() > 0) {
                        if (what == 1) {
                            page = 1;
                            searchString = edSearch.getText().toString();
                            pepDataList.clear();
                            AppApi.searchPep(page, 15, searchString, SearchToAddActivity.this, 0, SearchToAddActivity.this);

                        } else if (what == 2) {
                            page = 1;
                            searchString = edSearch.getText().toString();
                            groupDataList.clear();
                            AppApi.searchGroup(searchString, SearchToAddActivity.this, 1, SearchToAddActivity.this);

                        }
                    } else {
                        Toast.makeText(mContext, "搜索条件不能为空!", Toast.LENGTH_SHORT).show();
                    }
                }
                return false;
            }
        });


        EasyLoadingMoreView loadMoreView = new EasyLoadingMoreView();

        EasyLoadingMoreView groupLoadView = new EasyLoadingMoreView();

        View emptyView = getLayoutInflater().inflate(R.layout.empty_view, null);

        View groupEmptyView = getLayoutInflater().inflate(R.layout.empty_view, null);

        pepRyc.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new PepAdapter(R.layout.item_pep, pepDataList);
        pepRyc.setAdapter(adapter);
        adapter.setLoadMoreView(loadMoreView);
        adapter.setEmptyView(emptyView);
        adapter.setOnItemClickListener(this);
        adapter.setOnLoadMoreListener(this, pepRyc);


        groupRyc.setLayoutManager(new LinearLayoutManager(mContext));
        groupListAdapter = new GroupListAdapter(R.layout.item_joined_group, groupDataList);
        groupRyc.setAdapter(groupListAdapter);
        groupListAdapter.setLoadMoreView(groupLoadView);
        groupListAdapter.setEmptyView(groupEmptyView);
        groupListAdapter.setOnItemClickListener(this);
        groupListAdapter.setOnItemChildClickListener(this);
        groupListAdapter.setOnLoadMoreListener(this, groupRyc);
    }

    @OnClick({R.id.cancel, R.id.friend, R.id.circle_ll})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.cancel:
                finish();
                break;
            case R.id.friend:
                if (!TextUtils.isEmpty(edSearch.getText().toString())) {
                    loadingDialog.show();
                    searchString = edSearch.getText().toString();
                    pepRyc.setVisibility(View.VISIBLE);
                    groupRyc.setVisibility(View.INVISIBLE);
                    tipLl.setVisibility(View.INVISIBLE);
                    what = 1;
                    AppApi.searchPep(page, 15, searchString, SearchToAddActivity.this, 0, SearchToAddActivity.this);
                } else {
                    Toast.makeText(mContext, "请输入您要搜索的内容!", Toast.LENGTH_SHORT).show();
                }

                break;
            case R.id.circle_ll:
                if (!TextUtils.isEmpty(edSearch.getText().toString())) {
                    loadingDialog.show();
                    searchString = edSearch.getText().toString();
                    pepRyc.setVisibility(View.INVISIBLE);
                    groupRyc.setVisibility(View.VISIBLE);
                    tipLl.setVisibility(View.INVISIBLE);
                    what = 2;
                    AppApi.searchGroup(searchString, SearchToAddActivity.this, 1, SearchToAddActivity.this);
                } else {
                    Toast.makeText(mContext, "请输入您要搜索的内容!", Toast.LENGTH_SHORT).show();
                }

                break;
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

        if (adapter instanceof PepAdapter) {

            Intent intent = new Intent(mContext, PersonDetailsActivity.class);
            intent.putExtra("id", pepDataList.get(position).getUser_id());
            startActivity(intent);

        } else if (adapter instanceof GroupListAdapter) {
            Intent intent = new Intent(mContext, GroupDetailsActivity.class);
            intent.putExtra("id", groupDataList.get(position).getCommunity_id());
            startActivity(intent);
        }

    }

    @Override
    public void onLoadMoreRequested() {
        if (what == 1) {
            page++;
            AppApi.searchPep(page, 15, searchString, SearchToAddActivity.this, 0, SearchToAddActivity.this);
        } else if (what == 2) {

        }

    }

    @Override
    public void handlerSuccessData(String result, int tag) {
        loadingDialog.cancelDialog();
        switch (tag) {
            case 0:
                PepListBean pepListBean = JSON.parseObject(result, PepListBean.class);
                List<PepListBean.DataBeanX.DataBean> dataBeanList = pepListBean.getData().getData();
                pepDataList.addAll(dataBeanList);
                if (pepDataList.size() < 10) {
                    adapter.setEnableLoadMore(false);
                } else {
                    adapter.setEnableLoadMore(true);
                }
                if (isLoadMore) {
                    adapter.loadMoreComplete();
                    if (dataBeanList.size() == 0) {
                        adapter.loadMoreEnd();
                    }
                    isLoadMore = false;
                }
                adapter.notifyDataSetChanged();

                break;
            case 1:

                GroupListBean groupListBean = JSON.parseObject(result, GroupListBean.class);
                List<GroupListBean.DataBean> groupListBeanData = groupListBean.getData();
                groupDataList.addAll(groupListBeanData);
                if (groupListBeanData.size() < 10) {
                    groupListAdapter.setEnableLoadMore(false);
                } else {
                    groupListAdapter.setEnableLoadMore(true);
                }
                if (isLoadMore) {
                    groupListAdapter.loadMoreComplete();
                    if (groupListBeanData.size() == 0) {
                        groupListAdapter.loadMoreEnd();
                    }
                    isLoadMore = false;
                }
                groupListAdapter.notifyDataSetChanged();
                break;
            case 3:
                groupDataList.get(postion).setFollow(1);
                adapter.notifyItemChanged(postion);
                SnackUtils.show(mRootView,"关注成功！");
                break;
            case 2:
                groupDataList.get(postion).setFollow(0);
                adapter.notifyItemChanged(postion);
                SnackUtils.show(mRootView,"取关成功！");
                break;
        }

    }

    @Override
    public void handlerFailData(String failString, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    public void handleErrorData(String error, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        switch (view.getId()) {
            case R.id.item_bg:
                Intent intent = new Intent(mContext, GroupDetailsActivity.class);
                intent.putExtra("id", groupDataList.get(position).getCommunity_id());
                startActivity(intent);
                break;
            case R.id.add_care:
                if (MyUtils.getToken(mContext) != null && MyUtils.getToken(mContext).length() == 0) {
                    Toast.makeText(mContext, "您尚未登陆，请先登录！", Toast.LENGTH_SHORT).show();
                    Intent loginIntent = new Intent(mContext, LoginActivity.class);
                    startActivityForResult(loginIntent, 200);
                    return;
                }
                this.postion = position;
                loadingDialog.show();
                AppApi.addCareGroup(groupDataList.get(position).getCommunity_id(), SearchToAddActivity.this, 3, SearchToAddActivity.this);
                break;
            case R.id.cancel_care:
                if (MyUtils.getToken(mContext) != null && MyUtils.getToken(mContext).length() == 0) {
                    Toast.makeText(mContext, "您尚未登陆，请先登录！", Toast.LENGTH_SHORT).show();
                    Intent loginIntent = new Intent(mContext, LoginActivity.class);
                    startActivityForResult(loginIntent, 200);
                    return;
                }
                this.postion = position;
                TipDialogFragment tipDialogFragment = new TipDialogFragment();
                tipDialogFragment.setContent("确认取消关注此社群？");
                tipDialogFragment.setMyCallBack(SearchToAddActivity.this);
                tipDialogFragment.show(getSupportFragmentManager(), "tip");
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1) {
            if (requestCode == 200) {
                page = 1;
                groupDataList.clear();
                loadingDialog.show();
                AppApi.searchGroup(searchString, SearchToAddActivity.this, 1, SearchToAddActivity.this);
            }
        }
    }
}
